package ar.com.spsolutions.splibrary.utils;

import ar.com.spsolutions.splibrary.book.exceptions.ISBNException;

public class ISBNValidatorUtil {
	private ISBNValidatorUtil() {

	}

	// throw new ISBNException("El isbn debe de tener 8 o 13 digitos");

	public static void validate(final String aISBN) {
		if (aISBN == null) {
			throw new ISBNException("ISBN can't be null");
		}
		final String isbn = aISBN.replaceAll("(\\-|\\s)", "");
		if ((isbn.length() == 0) && !(ISBNValidatorUtil.checkISBN(aISBN))) {
			throw new ISBNException("Invalid ISBN");
		}
		if ((isbn.length() == 13) && !(ISBNValidatorUtil.checkEAN13(isbn))) {
			throw new ISBNException("Invalid ISBN");
		}
	}

	private static boolean checkEAN13(final String ean) {
		int evens = 0;
		int odds = 0;
		for (int i = 0; i <= (ean.length() - 2); i++) {
			if ((i % 2) == 0) {
				odds += Integer.parseInt(ean.substring(i, i + 1));
			} else {
				evens += Integer.parseInt(ean.substring(i, i + 1));
			}
		}
		if (ean.length() == 13) {
			evens *= 3;
		} else {
			odds *= 3;
		}
		final int checksum = evens + odds;
		int controleDigit = 10 - (checksum % 10);
		if (controleDigit == 10) {
			controleDigit = 0;
		}
		return (controleDigit == Integer
				.valueOf(ean.substring(ean.length() - 1)));
	}

	private static boolean checkISBN(final String aISBN) {
		int sum = 0;
		final int length = aISBN.length();
		for (int i = 0; i < (length - 1); i++) {
			sum += Integer.parseInt(String.valueOf(aISBN.charAt(i)))
					* (length - i);
		}
		final String lastDigit = String.valueOf(aISBN.charAt(length - 1));
		if (lastDigit.equalsIgnoreCase("x")) {
			sum += 10;
		} else {
			sum += Integer.valueOf(lastDigit);
		}
		int checkDigit = sum / 11;
		checkDigit = (sum - (checkDigit * 11));
		return checkDigit == 0;
	}

}
